package JavaCode;

/**
 * @Author Kechelle
 * @Date 2020/9/4 23:13
 * @Version 1.0
 */
public class Singleton {
    //单锁懒汉式
    private static Singleton singleton;

    private Singleton(){}

    public static synchronized Singleton getInstance(){
        if (singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}


//饿汉式
    /*private static Singleton singleton = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return singleton;
    }*/
//懒汉式
    /*private static Singleton singleton;
    private Singleton(){}
    public static Singleton getInstance(){
        if (singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }*/
//双重校验锁实现单例
    //使用 volatile 可以禁止 JVM 的指令重排，保证在多线程环境下也能正常运行。
    /*private volatile static Singleton singleton;
    private Singleton(){}
    public static Singleton getInstance(){
        //进入第一次判空
        if (singleton == null){
            synchronized (Singleton.class){
                if (singleton == null){
                    singleton =  new Singleton();
                }
            }
        }
        return singleton;
    }*/